package cn.momoshenchi.product.service.impl;

import cn.momoshenchi.common.constant.ProdcutConstant;
import cn.momoshenchi.common.to.SkuHasStockVo;
import cn.momoshenchi.common.to.SkuReductionTo;
import cn.momoshenchi.common.to.SpuBoundTo;
import cn.momoshenchi.common.utils.R;
import cn.momoshenchi.product.entity.*;
import cn.momoshenchi.product.feign.CouponFeignService;
import cn.momoshenchi.product.feign.SearchFeignService;
import cn.momoshenchi.product.feign.WareFeignService;
import cn.momoshenchi.product.service.*;
import cn.momoshenchi.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.momoshenchi.common.utils.PageUtils;
import cn.momoshenchi.common.utils.Query;

import cn.momoshenchi.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService
{

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;
@Autowired
private SearchFeignService searchFeignService;
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo)
    {
        //1.保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        save(spuInfoEntity);
        // 2.保存spu描述图片
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);

        //3.保存图片集
        List<String> images = spuSaveVo.getImages();
        spuImagesService.save(spuInfoEntity.getId(), images);

        //4.保存规则参数
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(item.getAttrId());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        //  5.保存sku信息
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0)
        {
            log.error("保存积分失败");
        }

        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && !skus.isEmpty())
        {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages())
                {
                    if (image.getDefaultImg() == 1)
                    {
                        defaultImg = image.getImgUrl();
                    }
                }
                //5.1 sku基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCategoryId(skuInfoEntity.getCategoryId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSaleCount(0L);
                skuInfoService.save(skuInfoEntity);

                //5.2  sku 图片信息  pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> !StringUtils.isBlank(entity.getImgUrl())).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);


                //5.3   销售属性   pms_sku_sale_attr
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());

                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //5.4 优惠信息,满减信息  sms
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0)
                {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0)
                    {
                        log.error("保存sku优惠失败");
                    }

                }

            });


        }


        //6.保存积分信息
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params)
    {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params)
    {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isBlank(key))
        {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });

        }
        String status = (String) params.get("status");
        if (!StringUtils.isBlank(status))
        {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isBlank(brandId) && !"0".equalsIgnoreCase(brandId))
        {
            wrapper.eq("brand_id", brandId);
        }
        String categoryId = (String) params.get("categoryId");
        if (!StringUtils.isBlank(categoryId) && !"0".equalsIgnoreCase(categoryId))
        {
            wrapper.eq("category_id", categoryId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), wrapper

        );
        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId
     */

    @Override
    @Transactional
    public void up(Long spuId)
    {
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getBySpuId(spuId);
        List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());


        //1.查询规格属性
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.baseAttrList(spuId);
        List<Long> attrIds = productAttrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> attrstemp = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(attrstemp);


        List<SkuEsModel.Attrs> attrsList = productAttrValueEntities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs2 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs2);
            return attrs2;
        }).collect(Collectors.toList());

        //2.查询库存
        List<SkuHasStockVo> data = new ArrayList<>();
        Map<Long, Boolean> hasStockMap =null;
        try
        {
            R r = wareFeignService.hasStock(skuIdList);

            if (r.getCode() != 0)
            {
                data = (List<SkuHasStockVo>) r.get("data");
                hasStockMap=data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        //3.查询所有sku信息, 进行封装
        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        List<SkuEsModel> skuEsModelList = skuInfoEntities.stream().map(item -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(item, esModel);
            esModel.setSkuImg(item.getSkuDefaultImg());
            esModel.setSkuPrice(item.getPrice());
            if(finalHasStockMap ==null)
            {
                esModel.setHasStock(true);
            }else
            {
                esModel.setHasStock(finalHasStockMap.get(item.getSkuId()));
            }
            esModel.setHotScore(0L);

            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(item.getCategoryId());
            if(categoryEntity!=null)
            esModel.setCategoryName(categoryEntity.getName());

            esModel.setAttrs(attrsList);

            return esModel;
        }).collect(Collectors.toList());
        R r = searchFeignService.productSave(skuEsModelList);
        if(r.getCode()==0)
        {
           baseMapper.updateStatus(spuId, ProdcutConstant.StatusEnum.SPU_UP.getCode());
        }

    }

}